package br.biofoco.p2p.utils;

import java.util.zip.CRC32;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.zip.CheckedInputStream;

public final class FileCRC {
	
	private FileCRC() {}

	public static long getChecksum(String filename) throws IOException, FileNotFoundException {

		long checksum = 0L;
		CheckedInputStream inputStream = null;

		try {
			try {
				inputStream = new CheckedInputStream(new FileInputStream(filename), new CRC32());
			} catch (FileNotFoundException e) {
				throw new FileNotFoundException("FileCRC.getCheckSum(): File not found!!! - " + e.getMessage());
			}
			byte[] buf = new byte[128];
			while (inputStream.read(buf) >= 0) {
			}
			checksum = inputStream.getChecksum().getValue();
		} catch (IOException e) {
			throw new IOException("FileCRC.getCheckSum() - Erro na leitura do arquivo: " + e.getMessage());
		}
		return checksum;
	}
	
}
